package com.wp.admin.controller;

import com.wp.admin.pojo.SysUser;
import com.wp.admin.pojo.SysUserToken;
import com.wp.admin.service.SysUserService;
import com.wp.admin.service.SysUserTokenService;
import com.wp.common.enums.ExceptionEnum;
import com.wp.common.exception.ScException;
import com.wp.common.utils.PasswordUtils;
import com.wp.model.admin.input.dto.LoginInputDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author wp
 * @create 2019-03-03 15:51
 */
@RestController
@Api(tags = "系统API")
public class SysLoginController {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserTokenService sysUserTokenService;

    @PostMapping("/sys/login")
    @ApiOperation(value = "用户登录", notes = "根据用户名和密码登录")
    public ResponseEntity<SysUserToken> login(@RequestBody LoginInputDTO loginInputDTO) {
        String userName = loginInputDTO.getUserName();
        String password = loginInputDTO.getPassword();
        String captcha = loginInputDTO.getCaptcha();
        if (StringUtils.isBlank(userName)) {
            throw new ScException(ExceptionEnum.USERNAME_CANNOT_BE_NULL);
        }
        if (StringUtils.isBlank(password)) {
            throw new ScException(ExceptionEnum.PASSWORD_CANNOT_BE_NULL);
        }
        if (StringUtils.isBlank(captcha)) {
            throw new ScException(ExceptionEnum.CAPTCHA_CANNOT_BE_NULL);
        }
        SysUser user = sysUserService.findByUserName(userName);
        if (user == null) {
            throw new ScException(ExceptionEnum.USER_NOT_FOUND);
        }
        if (!match(user, password)) {
            throw new ScException(ExceptionEnum.PASSWORD_NOT_RIGHT);
        }
        if (user.getStatus() == false) {
            throw new ScException(ExceptionEnum.INVILID_USER);
        }
        SysUserToken token = sysUserTokenService.createToken(user.getId());
        return ResponseEntity.ok(token);
    }

    /**
     * 匹配密码
     *
     * @param user
     * @param password
     * @return
     */
    private boolean match(SysUser user, String password) {
        return user.getPassword().equals(PasswordUtils.encrypte(password, user.getSalt()));
    }
}
